//
//  DKAuthorityHelper.m
//  DanKU
//
//  Created by 吴斌 on 2023/12/5.
//

#import "DKAuthorityHelper.h"
#import "ContactsUI/ContactsUI.h"
#import <CoreLocation/CoreLocation.h>
#import <EventKit/EventKit.h>
@interface DKAuthorityHelper()<CLLocationManagerDelegate>
@property (nonatomic, strong)CLLocationManager * dk_LocationManager;
@property (nonatomic, assign)BOOL isUpload;
@end
@implementation DKAuthorityHelper
static DKAuthorityHelper *defaultManager = nil;
+(DKAuthorityHelper*)defaultManager{
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        if(defaultManager == nil){
            defaultManager = [[self alloc] init];
        }
    });
    return defaultManager;
}
- (CLLocationManager *)dk_LocationManager{
    if(!_dk_LocationManager){
        _dk_LocationManager = [[CLLocationManager alloc] init];
        [_dk_LocationManager requestWhenInUseAuthorization];
        [_dk_LocationManager requestAlwaysAuthorization];
        [_dk_LocationManager startUpdatingLocation];
        _dk_LocationManager.delegate = self;
    }
    return _dk_LocationManager;
}
//照相机权限
+ (void)requestCameraAuthorization:(void(^)(DKAuthorizationStatus status))callback{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus == AVAuthorizationStatusNotDetermined) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    [self executeCallback:callback status:DKAuthorizationStatusAuthorized];
                } else {
                    [self executeCallback:callback status:DKAuthorizationStatusDenied];
                }
            }];
        } else if (authStatus == AVAuthorizationStatusAuthorized) {
            [self executeCallback:callback status:DKAuthorizationStatusAuthorized];
        } else if (authStatus == AVAuthorizationStatusDenied) {
            [self executeCallback:callback status:DKAuthorizationStatusDenied];
        } else if (authStatus == AVAuthorizationStatusRestricted) {
            [self executeCallback:callback status:DKAuthorizationStatusRestricted];
        }
    } else {
        [self executeCallback:callback status:DKAuthorizationStatusNotSupport];
    }
}
//通讯录权限
+ (void)requestAddressBookAuthorization:(void(^)(DKAuthorizationStatus status))callback{
    CNAuthorizationStatus authStatus =  [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (authStatus == CNAuthorizationStatusNotDetermined) {
        [[[CNContactStore alloc] init] requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                [self executeCallback:callback status:DKAuthorizationStatusAuthorized];
            } else {
                [self executeCallback:callback status:DKAuthorizationStatusDenied];
            }
        }];
    } else if (authStatus == CNAuthorizationStatusAuthorized) {
        [self executeCallback:callback status:DKAuthorizationStatusAuthorized];
    } else if (authStatus == CNAuthorizationStatusDenied) {
        [self executeCallback:callback status:DKAuthorizationStatusDenied];
    } else if (authStatus == CNAuthorizationStatusRestricted) {
        [self executeCallback:callback status:DKAuthorizationStatusRestricted];
    }
}
//定位权限
+ (void)requestLocationAuthorization:(BOOL)isUpload withAuthorization:(void(^)(DKAuthorizationStatus status))callback{
    [DKAuthorityHelper defaultManager].isUpload = isUpload;
    CLAuthorizationStatus authStatus = [CLLocationManager authorizationStatus];
    if (authStatus == kCLAuthorizationStatusNotDetermined) {
        [[DKAuthorityHelper defaultManager].dk_LocationManager startUpdatingLocation];
    } else if (authStatus == kCLAuthorizationStatusAuthorizedWhenInUse) {
        [self executeCallback:callback status:DKAuthorizationStatusAuthorized];
        [[DKAuthorityHelper defaultManager].dk_LocationManager startUpdatingLocation];
    } else if (authStatus == kCLAuthorizationStatusDenied) {
        [self executeCallback:callback status:DKAuthorizationStatusDenied];
    } else if (authStatus == kCLAuthorizationStatusRestricted) {
        [self executeCallback:callback status:DKAuthorizationStatusRestricted];
    }
}
//日历权限
+ (void)requestEventAuthorization:(void(^)(DKAuthorizationStatus status))callback{
    EKAuthorizationStatus authStatus = [EKEventStore  authorizationStatusForEntityType:EKEntityTypeEvent];
    if (authStatus == EKAuthorizationStatusNotDetermined) {
        EKEventStore *store = [[EKEventStore alloc] init];
        [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError * _Nullable error) {
            if (error) {
                [self executeCallback:callback status:DKAuthorizationStatusDenied];
            }else {
              if (granted) {
                  [self executeCallback:callback status:DKAuthorizationStatusAuthorized];
              }else {
                  [self executeCallback:callback status:DKAuthorizationStatusDenied];
              }
            }
        }];
    } else if (authStatus == EKAuthorizationStatusAuthorized) {
        [self executeCallback:callback status:DKAuthorizationStatusAuthorized];
    } else if (authStatus == EKAuthorizationStatusDenied) {
        [self executeCallback:callback status:DKAuthorizationStatusDenied];
    } else if (authStatus == EKAuthorizationStatusRestricted) {
        [self executeCallback:callback status:DKAuthorizationStatusRestricted];
    }
}
#pragma mark - callback
+ (void)executeCallback:(void (^)(DKAuthorizationStatus))callback status:(DKAuthorizationStatus)status {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (callback) {
            callback(status);
        }
    });
}
#pragma mark CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    WeakSelf(self)
    CLLocation *newLocation = locations.firstObject;
    NSLog(@"经度%f，纬度%f",newLocation.coordinate.longitude,newLocation.coordinate.latitude);
    [DKGlobalHelper defaultManager].dk_LocationMdl = [[DKLocationModel alloc] init];
    [DKGlobalHelper defaultManager].dk_LocationMdl.longitude = [NSString stringWithFormat:@"%f",newLocation.coordinate.longitude];
    [DKGlobalHelper defaultManager].dk_LocationMdl.latitude = [NSString stringWithFormat:@"%f",newLocation.coordinate.latitude];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0){
             CLPlacemark *placemark = [placemarks objectAtIndex:0];
             //获取城市
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
             NSLog(@"location -- 省:%@, 市：%@， 区：%@ 街道：%@", placemark.administrativeArea, city, placemark.subLocality, placemark.name);
            [DKGlobalHelper defaultManager].dk_LocationMdl.administrativeArea = placemark.administrativeArea;
            [DKGlobalHelper defaultManager].dk_LocationMdl.city = city;
            [DKGlobalHelper defaultManager].dk_LocationMdl.subLocality = placemark.subLocality;
            [DKGlobalHelper defaultManager].dk_LocationMdl.jieName = placemark.name;
            [weakSelf.dk_LocationManager stopUpdatingLocation];
            if([DKAuthorityHelper defaultManager].isUpload){
                [[DKAuthExtHelper defaultManager] uploadDeviceInfoBook];
            }
        }
        
    }];
}
//- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
//    NSLog(@"经度%f，纬度%f",newLocation.coordinate.longitude,newLocation.coordinate.latitude);
//    [DKGlobalHelper defaultManager].dk_LocationMdl = [[DKLocationModel alloc] init];
//    [DKGlobalHelper defaultManager].dk_LocationMdl.longitude = [NSString stringWithFormat:@"%f",newLocation.coordinate.longitude];
//    [DKGlobalHelper defaultManager].dk_LocationMdl.latitude = [NSString stringWithFormat:@"%f",newLocation.coordinate.latitude];
//
//    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//        if (placemarks.count > 0){
//             CLPlacemark *placemark = [placemarks objectAtIndex:0];
//             //获取城市
//             NSString *city = placemark.locality;
//             if (!city) {
//                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
//                 city = placemark.administrativeArea;
//             }
//             NSLog(@"location -- 省:%@, 市：%@， 区：%@ 街道：%@", placemark.administrativeArea, city, placemark.subLocality, placemark.name);
//            [DKGlobalHelper defaultManager].dk_LocationMdl.administrativeArea = placemark.administrativeArea;
//            [DKGlobalHelper defaultManager].dk_LocationMdl.city = city;
//            [DKGlobalHelper defaultManager].dk_LocationMdl.subLocality = placemark.subLocality;
//            [DKGlobalHelper defaultManager].dk_LocationMdl.jieName = placemark.name;
//        }
//    }];
//    [self.dk_LocationManager stopUpdatingLocation];
//}
//-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
//    [self.dk_LocationManager stopUpdatingLocation];
//    CLLocation *location = [locations lastObject];
//    CLLocationCoordinate2D coordinate = location.coordinate;
//    NSLog(@"经度%f，纬度%f",coordinate.longitude,coordinate.latitude);
//}
@end
